package examples.webstore.service;


import java.util.List;

import edu.scsu.csci.annotation.ADomainObject;
import edu.scsu.csci.annotation.AExpose;
import edu.scsu.csci.annotation.AInterceptor;
import edu.scsu.csci.annotation.AScope;
import edu.scsu.csci.annotation.AView;
import edu.scsu.csci.annotation.validator.AValidate;
import edu.scsu.csci.controller.WebUtils;
import edu.scsu.csci.core.EScope;
import examples.webstore.domainobject.Product;
import examples.webstore.domainobject.User;
import examples.webstore.interceptor.Audit;

@AExpose(expose = true, allow= {"authenticate", "logout"})
public class LoginService {

	/**
	 * <p>	authenticates the user.
	 * 
	 * @param user 
	 * @return 
	 */
	public boolean authenticate(User user)	{
		user = User.getUsers().get(user.getName());
		if(user == null){
			WebUtils.setExecutionError(" ", "The User Id and password specified does not exist.");
			return false;
		}
		WebUtils.getSession().setAttribute("User", user);
		return true;		
	} 
	
	/**
	 * <pre>
	 * 		The user needs to be authenticated.
	 * </pre>
	 * <p>	returns the list product to the user.
	 */
	@ADomainObject(clazz = User.class, scope = EScope.REQUEST)
	@AInterceptor(interceptors = {Audit.class})
	@AScope(key="productList")
	@AView(resourceName = "productList", errorResourceName = "Login")
	@AValidate(method="authenticate")
	public List<Product> displayCatalog(User user){
		user = (User) WebUtils.getSession().getAttribute("User");
		return Product.displayList(user.getZipCode());
	}
	
	
	@ADomainObject(clazz = User.class, scope = EScope.SESSION)
	@AView(resourceName = "Login", errorResourceName = "Login")
	public void logout(User user){
		//do something
		WebUtils.getSession().invalidate(); 
	}
}
